/*******************************************************************************
* Long-term effects of weather-induced migration on urban labor and housing 
  markets
* Busso & Chauvin

* Purpose: Script to create SPEI drought index.

*******************************************************************************/

/***************************************************************/
/* Droughts main variable */
/***************************************************************/ 
/* Data */
* Load SPEI-12 data
use "$db_inp/spei12_yearly_mca8010", replace

* Keep only years 1980-2009
keep if year >= 1980 & year <= 2010

* make it a month-level variable
reshape long month, i(mca8010 year) j(mth)
rename month spei
rename mth month
order mca8010 year month spei
sort mca8010 year month spei

* Revert spei values
replace spei = -spei

/* Dummies for drought shock groups */
* 10 years (2010 Census only)
gen y0009 = (year > 1999 & year <= 2009)

/* Non-discounted version of SPEI-12 */
gen double spei_0009 = y0009*spei
replace spei_0009 = . if spei_0009 == 0

/* Considering both dry and wet months */
collapse (mean) drought_dws0009 = spei_0009, by(mca8010)

lab var drought_dws0009 "SPEI*(-1), simple monthly average, 0009 period"
		
* Save final dataset
save "$db_tmp/drought_index_spei8010.dta", replace

/***************************************************************/
/* Droughts control variable */
/***************************************************************/ 
* Load SPEI-12 data
use "$db_inp/spei12_yearly_mca8010", replace

* Keep only years 1980-2009
keep if year >= 1951 & year <= 2000

* make it a month-level variable
reshape long month, i(mca8010 year) j(mth)
rename month spei
rename mth month
order mca8010 year month spei
sort mca8010 year month spei

* Revert spei  values
replace spei = -spei

/* Dummies for drought shock */
gen y8190 = (year >= 1981 & year <= 1990)

/* Non-discounted version of SPEI-12 */
gen double spei_8190 = y8190*spei
replace spei_8190 = . if spei_8190 == 0

/* Index: simple average */
collapse (mean) drought_dws8190 = spei_8190, by(mca8010)

lab var drought_dws8190 "SPEI*(-1), simple monthly average, 8190 period"

* Save final dataset
save "$db_tmp/drought_controls_spei8010.dta", replace
